package cn.iocoder.yudao.module.enterprise.service.enterpriseJob;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.enterprise.controller.admin.enterpriseJob.vo.*;
import cn.iocoder.yudao.module.enterprise.convert.enterpriseJob.EnterpriseJobConvert;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.company.EnterpriseCompanyDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.enterpriseJob.EnterpriseJobDO;
import cn.iocoder.yudao.module.enterprise.dal.mysql.company.EnterpriseCompanyMapper;
import cn.iocoder.yudao.module.enterprise.dal.mysql.enterpriseJob.enterpriseJobMapper;
import cn.iocoder.yudao.module.member.api.job.JobApi;
import cn.iocoder.yudao.module.system.api.message.MessageApi;
import cn.iocoder.yudao.module.system.api.message.dto.MessageCreateReqDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.JOB_IMPORT_IS_EXISTS;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.JOB_NOT_EXISTS;

/**
 * 招聘职位 Service 实现类
 *
 * @author 谭万全
 */
@Service
@Validated
public class EnterpriseJobServiceImpl implements EnterpriseJobService {

    @Resource
    private enterpriseJobMapper enterpriseJobMapper;
    @Resource
    private EnterpriseCompanyMapper enterpriseCompanyMapper;
    @Resource
    private MessageApi messageApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private JobApi jobApi;
    @Override
    public Long createJob(EnterpriseJobCreateReqVO createReqVO) {
        // 插入
        EnterpriseJobDO job = EnterpriseJobConvert.INSTANCE.convert(createReqVO);
        AdminUserRespDTO loginUser=adminUserApi.getUser(SecurityFrameworkUtils.getLoginUserId());
        job.setStatus("0"); // 新增职位状态默认为编辑中的草稿状态
        job.setUserId(loginUser.getId());
        job.setDeptId(loginUser.getDeptId());
        job.setUpdater(loginUser.getUserName());
        job.setOperation(loginUser.getUserName());
        job.setCreator(loginUser.getUserName());
        enterpriseJobMapper.insert(job);
        //发送站内信给企业
        Map<String, Long> phones=jobApi.getCompanyAdminCreatorPhone(job.getId(),createReqVO.getCompanyId());
        String title=job.getJobName()+"：职位创建成功";
        String message="您好，"+job.getJobName()+"职位创建成功，创建人"+loginUser.getNickname();
        for(String key:phones.keySet()){
            Long id = phones.get(key);
            sendmessage(1l,id,title,message);
        }
        //发送站内信给运营
         title=createReqVO.getCompanyName()+"-"+job.getJobName()+"：职位提交审核";
         message="您好，"+createReqVO.getCompanyName()+"-"+job.getJobName()+"提交审核，提交人："+loginUser.getNickname()+"请查收";
        List<Long> ids= adminUserApi.getUserIdsByTenant(2l);
        for (Long id1:ids) {
            sendmessage(1l,id1,title,message);
        }
        // 返回
        return job.getId();
    }
    @Async
    void sendmessage(Long type, Long id, String title, String messageText){
        MessageCreateReqDTO messageCreateReqVO=new MessageCreateReqDTO();
        messageCreateReqVO.setPhone("");
        messageCreateReqVO.setType(type);
        messageCreateReqVO.setStatus("5");
        messageCreateReqVO.setUserId(id);
        messageCreateReqVO.setStudentName("系统管理员");
        messageCreateReqVO.setRemark(messageText);
        messageCreateReqVO.setTitle(title);
        messageApi.sendMessage(messageCreateReqVO);
    }
    private  static final HashMap<String,String> educationMap =new HashMap<String, String>();
    static{
        educationMap.put("大专-大一", "[1,2]");
        educationMap.put("大专-大二", "[1,3]");
        educationMap.put("大专-大三", "[1,4]");
        educationMap.put("本科-大一", "[5,6]");
        educationMap.put("本科-大二", "[5,7]");
        educationMap.put("本科-大三", "[5,8]");
        educationMap.put("本科-大四", "[5,9]");
        educationMap.put("硕士-研一", "[10,11]");
        educationMap.put("硕士-研二", "[10,12]");
        educationMap.put("硕士-研三", "[10,13]");
        educationMap.put("博士", "[14,15]");
    }
    @Override
    public void updateJob(EnterpriseJobUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateJobExists(updateReqVO.getId());
        // 更新
        EnterpriseJobDO updateObj = EnterpriseJobConvert.INSTANCE.convert(updateReqVO);
        updateObj.setUpdater(SecurityFrameworkUtils.getLoginUser().getUsername());
        updateObj.setOperation(SecurityFrameworkUtils.getLoginUser().getUsername());
        enterpriseJobMapper.updateById(updateObj);
    }

    @Override
    public void updateJobsDate(List<EnterpriseJobUpdateReqVO> updateReqVOs) {
        for (EnterpriseJobUpdateReqVO updateReqVO:updateReqVOs) {
            updateReqVO.setPublishTime(new Date());
            // 校验存在
            this.validateJobExists(updateReqVO.getId());
            // 更新
            EnterpriseJobDO updateObj = EnterpriseJobConvert.INSTANCE.convert(updateReqVO);
            updateObj.setUpdater(SecurityFrameworkUtils.getLoginUser().getUsername());
            enterpriseJobMapper.updateById(updateObj);
        }
    }

    @Override
    public void setJobsTopStatus(@Valid List<Long> ids, String status) {
        // 更新
        //将ids转成list集合
        LoginUser loginUser=SecurityFrameworkUtils.getLoginUser();
        ids.forEach(v->{
            EnterpriseJobDO EnterpriseJobDO= new EnterpriseJobDO();
            EnterpriseJobDO.setId(v);
            EnterpriseJobDO.setOperation(loginUser.getUsername());
            EnterpriseJobDO.setTopStatus(status);
            EnterpriseJobDO.setUpdater(null);
            enterpriseJobMapper.updateById(EnterpriseJobDO);
        });

    }
    @Override
    public void setJobStatus(@Valid List<Long> ids) {
        // 更新
        LoginUser loginUser=SecurityFrameworkUtils.getLoginUser();
        //将ids转成list集合
        ids.forEach(v->{
            EnterpriseJobDO EnterpriseJobDO= new EnterpriseJobDO();
            EnterpriseJobDO.setId(v);
            EnterpriseJobDO.setOperation(loginUser.getUsername());
            EnterpriseJobDO.setStatus("enable");
            enterpriseJobMapper.updateById(EnterpriseJobDO);
        });

    }

    @Override
    public void setJobStatus(@Valid List<Long> ids, String status) {
        //将ids转成list集合
        LoginUser loginUser=SecurityFrameworkUtils.getLoginUser();
        ids.forEach(v->{
            EnterpriseJobDO EnterpriseJobDO= new EnterpriseJobDO();
            EnterpriseJobDO.setId(v);
            EnterpriseJobDO.setOperation(loginUser.getUsername());
            EnterpriseJobDO.setStatus(status);
            enterpriseJobMapper.updateById(EnterpriseJobDO);
        });
    }

    @Override
    public void deleteJob(@Valid List<Long> ids) {
        // 更新

        //将ids转成list集合
        ids.forEach(v->{
            EnterpriseJobDO jobDO= new EnterpriseJobDO();
            jobDO.setId(v);
            jobDO.setDeleted(true);
            jobDO.setUpdater(WebFrameworkUtils.getLoginUserName());
            jobDO.setUpdateTime(new Date());
            enterpriseJobMapper.updateById(jobDO);
            enterpriseJobMapper.deleteById(jobDO);
        });

    }

    @Override
    public void examinJob(EnterpriseJobUpdateReqVO updateReqVO) {
        this.updateJob(updateReqVO);
    }


    @Override
    public void deleteJob(Long id) {
        // 校验存在
        this.validateJobExists(id);
        // 删除
        EnterpriseJobDO job=new EnterpriseJobDO();
        job.setUpdater(WebFrameworkUtils.getLoginUserName());
        job.setUpdateTime(new Date());
        job.setOperation(SecurityFrameworkUtils.getLoginUser().getUsername());
        job.setId(id);
        enterpriseJobMapper.updateById(job);
        enterpriseJobMapper.deleteById(id);
    }

    private void validateJobExists(Long id) {
        if (enterpriseJobMapper.selectById(id) == null) {
            throw exception(JOB_NOT_EXISTS);
        }
    }

    @Override
    public EnterpriseJobDO getJob(Long id) {
        return enterpriseJobMapper.selectById(id);
    }

    @Override
    public List<EnterpriseJobDO> getJobList(Collection<Long> ids) {
        return enterpriseJobMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<EnterpriseJobDO> getJobPage(EnterpriseJobPageReqVO pageReqVO) {
       List<String> statusList=pageReqVO.getStatus();
        PageResult<EnterpriseJobDO> result = enterpriseJobMapper.selectPage(pageReqVO, statusList);
        if(null!=result && CollectionUtils.isNotEmpty(result.getList())){
            result.getList().stream().forEach(m->{
                m.setPostCount(enterpriseJobMapper.getResumeCount(m.getId()));
            });
        }
        return result;
    }

    @Override
    public List<EnterpriseJobDO> getJobList(EnterpriseJobExportReqVO exportReqVO) {
        return enterpriseJobMapper.selectList(exportReqVO);
    }


    @Override
    public PageResult<EnterpriseJobDO> getJobWaitExaminePage(EnterpriseJobPageReqVO pageReqVO,List<String> flag) {
        return enterpriseJobMapper.getJobWaitExaminePage(pageReqVO,flag);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public JobImportRespVO importJob(List<EnterpriseJobImputReqVO>  importJobs, Boolean updateSupport){
        if (CollUtil.isEmpty(importJobs)) {
            throw exception(JOB_IMPORT_IS_EXISTS);
        }
        LoginUser loginUser=SecurityFrameworkUtils.getLoginUser();
        Long companyId=loginUser.getCompanyId();
        EnterpriseCompanyDO companyDO=enterpriseCompanyMapper.selectById(companyId);
        JobImportRespVO respVO = JobImportRespVO.builder().createJobnames(new ArrayList<>())
                .updateJobnames(new ArrayList<>()).failureJobnames(new LinkedHashMap<>()).build();
        importJobs.forEach(importJob -> {
            EnterpriseJobDO enterpriseJobDO=EnterpriseJobConvert.INSTANCE.convert(importJob);
            String education=importJob.getEducation();
            String city=importJob.getCity();
            enterpriseJobDO.setEducation(covenEducation(education));
            enterpriseJobDO.setCity(covenCity(city));
            enterpriseJobDO.setCompanyId(companyDO.getId());
            enterpriseJobDO.setCompanyName(companyDO.getCompanyName());
            enterpriseJobDO.setCompanyLogo(companyDO.getCompanyLogo());
            enterpriseJobDO.setIndustry(companyDO.getIndustry());
            enterpriseJobDO.setSalaryUnit("daily_salary");
            enterpriseJobDO.setUserId(loginUser.getId());
            enterpriseJobDO.setPublishTime(new Date());
            enterpriseJobDO.setCreator(loginUser.getUsername());
            enterpriseJobDO.setDepartment(importJob.getDepartment());
            enterpriseJobDO.setWelfareTags(covenWelfareTags(importJob.getWelfareTags()));
            // 判断如果不存在，在进行插入
            enterpriseJobMapper.insert(enterpriseJobDO);
            respVO.getUpdateJobnames().add(importJob.getJobName());
        });

        return respVO;
    }

    private static String covenCity(String city){
        return "[\""+city.replace("-","\",\"")+"\"]";
    }

    private static String covenEducation(String educationJSON){
        if(educationJSON.indexOf("，")!=-1){
            educationJSON= educationJSON.replaceAll("，",",");
        }
        String[] educations=educationJSON.split(",");
        StringBuffer str=new StringBuffer("[");
        for (int i=0;i<educations.length;i++){
            if(educations[i]==null){
                continue;
            }
            str.append(educationMap.get(educations[i]));
            if(i!=educations.length-1){
                str.append(",");
            }else{
                str.append("]");
            }
        }
        return str.toString();
    }
    private static String covenWelfareTags(String welfareTagsJSON){
        if(welfareTagsJSON.indexOf("，")!=-1){
            welfareTagsJSON= welfareTagsJSON.replaceAll("，",",");
        }
        String[] welfareTags=welfareTagsJSON.split(",");
        StringBuffer str=new StringBuffer("[");
        for (int i=0;i<welfareTags.length;i++){
            if(welfareTags[i]==null){
                continue;
            }
            str.append("\""+welfareTags[i]+"\"");
            if(i!=welfareTags.length-1){
                str.append(",");
            }else{
                str.append("]");
            }
        }
        return str.toString();
    }

    @Override
    public EnterpriseJobCensusRespVO getEnterpriseJobCensus(Integer type,String startDate,String endDate,Long jobId) {
        Map<String,Object> param=new HashMap<>();
        Long companyId = SecurityFrameworkUtils.getLoginUser().getCompanyId();
        if(null==companyId){
            throw new NullPointerException("企业未登录,请先登录");
        }
        if(type!=0){
            if(1==type){
                if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
                    throw new NullPointerException("开始结束时间不能为空");
                }
            }else if(2==type){
                startDate=DateUtils.getWeekStart(new Date());
                endDate=DateUtils.format(new Date());
            }else if(3==type){
                startDate=DateUtils.getMonthStart();
                endDate=DateUtils.format(new Date());
            }
            if(startDate.length()>12){
                param.put("startDate",startDate );
                param.put("endDate",endDate );
            }else{
                param.put("startDate",startDate+" 00:00:00");
                param.put("endDate",endDate+" 23:59:59");
            }
        }
        if(null!=jobId){
            param.put("jobId",jobId);
        }
        param.put("companyId",companyId);
        EnterpriseJobCensusRespVO enterpriseJobCensus = enterpriseJobMapper.getEnterpriseJobCensus(param);
        //平台概览
        if(null==jobId && null!=enterpriseJobCensus){
            List<String> futureDate = DateUtils.getFutureDate(7);
            enterpriseJobCensus.setJobList(enterpriseJobMapper.getEnterpriseJobLastDay(companyId,futureDate));
        }
        //招聘职位
        if(null!=jobId && null!=enterpriseJobCensus){
            List<EnterpriseJobViewCountVO> newViewList;
            String nextMonth12 = DateUtils.getNextMonth12(12);
            List<String> lastMonth12 = DateUtils.getLastMonth12();
            List<EnterpriseJobViewCountVO> JobViewCount = enterpriseJobMapper.getEnterpriseJobViewCount(jobId, nextMonth12 + " 00:00:00");
            if(CollectionUtils.isNotEmpty(JobViewCount)){
                newViewList=new ArrayList<>();
                for (String month:lastMonth12){
                    EnterpriseJobViewCountVO v = JobViewCount.stream().filter(m -> month.equals(m.getCensusMonth())).findFirst().orElse(null);
                    if(null==v){
                        EnterpriseJobViewCountVO pv=new EnterpriseJobViewCountVO();
                        pv.setNum(0L);
                        pv.setCensusMonth(month);
                        newViewList.add(pv);
                    }else{
                        newViewList.add(v);
                    }
                }
                enterpriseJobCensus.setViewCountList(newViewList);
            }
            List<EnterpriseJobViewCountVO> sendRecordCount = enterpriseJobMapper.getEnterpriseVitaeSendRecordCount(jobId, nextMonth12);
            if(CollectionUtils.isNotEmpty(sendRecordCount)){
                newViewList=new ArrayList<>();
                for (String month:lastMonth12){
                    EnterpriseJobViewCountVO v = sendRecordCount.stream().filter(m -> month.equals(m.getCensusMonth())).findFirst().orElse(null);
                    if(null==v){
                        EnterpriseJobViewCountVO pv=new EnterpriseJobViewCountVO();
                        pv.setNum(0L);
                        pv.setCensusMonth(month);
                        newViewList.add(pv);
                    }else{
                        newViewList.add(v);
                    }
                }
                enterpriseJobCensus.setJobSendList(newViewList);
            }
            EnterpriseJobCensusRespVO respVO=enterpriseJobMapper.getVitaeSendRecordCensus(param);
            enterpriseJobCensus.setWomanSendNum(respVO.getWomanSendNum());
            enterpriseJobCensus.setManSendNum(respVO.getManSendNum());
            enterpriseJobCensus.setPcSendNum(respVO.getPcSendNum());
            enterpriseJobCensus.setAppletSendNum(respVO.getAppletSendNum());

        }
        return enterpriseJobCensus;
    }

    @Override
    public EnterpriseJobDO getRecoveryMemberJobById(Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id",id);
        List<EnterpriseJobDO> list = enterpriseJobMapper.recoveryEnterpriseJobPage(null, params);
        if(CollectionUtils.isNotEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    @Override
    public void updateBatchRecoveryEnterpriseJob(List<Long> ids) {
        enterpriseJobMapper.updateBatchRecoveryEnterpriseJob(ids);
    }

    @Override
    public PageResult<EnterpriseJobDO> recoveryEnterpriseJobPage(EnterpriseJobPageReqVO pageReqVO) {
        // MyBatis Plus 查询
        IPage<EnterpriseJobDO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(pageReqVO.getCompanyName())){
            params.put("companyName",pageReqVO.getCompanyName());
        }
        if(StringUtils.isNotBlank(pageReqVO.getCity())){
            params.put("city",pageReqVO.getCity());
        }
        if(StringUtils.isNotBlank(pageReqVO.getJobName())){
            params.put("jobName",pageReqVO.getJobName());
        }
        if(StringUtils.isNotBlank(pageReqVO.getUpdater())){
            params.put("updater",pageReqVO.getUpdater());
        }
        mpPage.setRecords(enterpriseJobMapper.recoveryEnterpriseJobPage(mpPage, params));
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }

    @Override
    public void updateEnterpriseJobFixed(Long id, Integer timingStatus, String fixedTime) {
        enterpriseJobMapper.updateEnterpriseJobFixed(id,timingStatus,fixedTime);
    }
}
